$(function(){
	
	/*
	 * 初始化活动时间
	 */
	var tody = new Date();
	$('.event-time').datetimepicker({
		dayViewHeaderFormat: 'YYYY MMMM',
		locale: 'zh-cn',
		format: 'YYYY-MM-DD HH:mm:ss',
		keepInvalid: true,
		minDate:tody
	});	
	$('#begin-time,#end-time').data('DateTimePicker').useCurrent(false);
	$("#begin-time").on("dp.change", function (e) {
		$('#end-time').data("DateTimePicker").minDate(e.date);
	});
	$("#end-time").on("dp.change", function (e) {
		$('#begin-time').data("DateTimePicker").maxDate(e.date);
	});
	
	
	/*
	 * 行政地区选择器初始化
	 */
	for (var i = 0; i < BTREGION.length; i++) {
		var area = {id:BTREGION[i].id,name:BTREGION[i].cname,level:BTREGION[i].level,parentId:BTREGION[i].upid};
		BTREGION[i] = area;
	}

	var regionInitor = {
		regionTplStr: $('#region-choocer-tpl').html(),
		initRegionEle : function ($ele) {
			var $replacer = $(swig.render(this.regionTplStr,{locals:{id:Math.round(Math.random()*1000)}}));
			$replacer.find('.address').replaceWith($ele.clone().attr('data-toggle','dropdown').attr('data-result',$ele.val()));
			$ele.replaceWith($replacer);
			$replacer.chineseRegion('source',BTREGION);
			$replacer.on('changed.bs.chinese-region',function(e,areas){
				  //areas是已选择的地区数据，按先选择的在最前的方式排序。
				  $(this).attr('data-result',areas[areas.length-1]['id']);
				  $(this).find('input').attr('data-result',areas[areas.length-1]['id']);
			});
		}
	};
	
	$('input.address').each(function() {
		regionInitor.initRegionEle($(this));
	});
	
	/*
	 * 初始化活动详情验证
	 */
	var $eventForm = $('#event-form');

	$eventForm.validate({
		rules: {
			'event-title': {
				required: true	
			},
			'startTime': {
				required: true	
			},
			'endTime': {
				required: true	
			},
			'event-type': {
				required: true	
			},
			'event-range': {
				required: true
			},
			'price': {
				required: true,
				number: true
			},
			'vipPrice': {
				required: true,
				number: true
			},
			'vipRecommonedPrice': {
				required: true,
				number: true
			},
			'qualityPrice': {
				required: true,
				number: true
			},
			'content': {
				required: true,
			},
			'contactMobile': {
				number: true
			},
			'totalNum': {
				required: true,
				number: true
			},
			'noVipNum': {
				required: true,
				number: true
			}
	    },
		messages: {
			'event-title': {
				required: '请输入活动标题'
			}	
	    },
		showErrors: function(errorMap,errorList) {
			if(errorList.length > 0) {
				var firstErr = errorList[0];
				var $errEle = $(firstErr.element);
				var $tooltipCon = null;
				if($errEle.attr('name') == 'event-range') {
					$tooltipCon = $errEle.parents('.form-group').find('label:first');
				} else if ($errEle.attr('name') == 'event-type') {
					greeting({
						title: '提示',
						msg: '活动类型至少选择1个'
					})
				} else {
					$tooltipCon = $errEle;
				}
				try{
					$tooltipCon.tooltip('hide').tooltip('destroy').tooltip({
						title: firstErr.message
					}).tooltip('show');
					$errEle.one('change focusout',function(){
						$tooltipCon.tooltip('hide').tooltip('destroy');
					});
				} catch(e) {
				}
			}
		},
		submitHandler: function() {
			submitEvent();
	    }
	});
	
	$('#event-save-btn').on('click',function(){
		//添加操作
		if(!$('input[name="id"]').val()>0){
			$("#eventStatus").val(0);
		}
		$eventForm.submit();
	});
	
	$('#event-savePub-btn').on('click',function(){
		$("#eventStatus").val(1);
		$eventForm.submit();
	});
	
	$('#event-cancel-btn').on('click',function(){
		$('#event-del-modal').modal('show');
	});
	
	//取消活动
	$('#event-cancel-submit').on('click',function(){
		var formData = {
			eventId: $("#eventId").val(),
			cancelReason: $("#cancelReason").val()
		};
		if(formData.cancelReason.trim()==""){
			greeting({title:'提示',msg:'请填写活动取消原因'});
			return false;
		}
		$('#event-del-modal').modal('hide');
		cAjax({
			url: '/cms/event/cancelEvent',
			data: formData,
			success: function(obj) {
				greeting({msg:'活动取消成功',confirm:function(){window.location.href="/cms/event/list?type=1";}});
			}
		});
	});
	

	function submitEvent() {
		if($('.pic:visible',$picContainer).length == 0) {
			greeting({
				title: '提示',
				msg: '请至少上传1张主题图'
			});		
			return false;
		} 
		if($.trim(eventEditor.getData()).length == 0) {
			greeting({
				title: '提示',
				msg: '请填写活动详情'
			});		
			return false;
		}
		var totalNum = $('input[name="totalNum"]').val();
		var noVipNum = $('input[name="noVipNum"]').val();
		if(parseInt(totalNum) < parseInt(noVipNum)){
			greeting({
				title: '提示',
				msg: '总人数必须大于非岛亲数'
			});		
			return false;
		}

		/*主题图url数组*/
		var topicPics = [];		
		$(':visible>[name="topicPic"]').each(function(){
			var $this = $(this);
			topicPics.push($this.val());
		});
		/*行业标签数据*/
		var tagIdArr = [];	
		$('#industry-tags input:checked').each(function(){
			tagIdArr.push($(this).val());
		});

		/*嘉宾数据数组*/
		var guestObjArr = [];
		$('.guest-thumb').each(function(){
			var $this = $(this);
			var guestDataObj = {};	
			$('input',$this).each(function(){
				var $this = $(this);
				guestDataObj[$this.attr('name')] = $this.val();
			});
			guestObjArr.push(guestDataObj);
		});
		var formData = {
			headImages: JSON.stringify(topicPics),
			honorGuests: JSON.stringify(guestObjArr)
		};
		formData['category'] = JSON.stringify(tagIdArr);
		$('input,#lng,#lat,input[name="id"]').each(function(){
			var $this = $(this);
			formData[$this.attr('name')] = $this.val();
		});
		formData['content'] = eventEditor.getData();
		formData['cityId'] = $('input[name="cityId"]').data("result");
		
		formData['sceneMaxImage'] = $('#sceneMaxImage').val();
		formData['sceneBackImage'] = $('#sceneBackImage').val();
		formData['isScene'] = $('input[name="isScene"]:checked').val();

		formData['extendContents'] = $('#extendContents').val();
		formData['userLimitLevel'] = $('#userLimitLevel').val();
		formData['countryCode'] = $('#countryCode').val();		
		console.log(formData);
		var url='/cms/event/add';
		if($('input[name="id"]').val()>0){
			url = '/cms/event/edit'
		}
		
		//弹窗禁止重复提交
		$("#banned-resave").modal("show");
		
		cAjax({
			url: url,
			data: formData,
			success: function(obj) {
				//console.log(obj);
				window.location.href="/cms/event/list?type=1";
			}
		});

	}



	/*
	 * 初始化活动详情编辑器
	 */
	var eventEditor = CKEDITOR.replace( 'event-detail-editor',{
		language: 'zh-cn',
		toolbar : 'Basic',
		height: 480,
		uiColor : '#FFFFFF',
		extraPlugins : 'uploadimage',
		uploadUrl : '/base/upload/uploadFile',
		filebrowserUploadUrl : '/base/upload/uploadFile',
		toolbarGroups : [
				{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
				{ name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
				{ name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },
				{ name: 'forms', groups: [ 'forms' ] },
				{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
				{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },
				{ name: 'links', groups: [ 'links' ] },
				{ name: 'insert', groups: [ 'insert' ] },
				{ name: 'styles', groups: [ 'styles' ] },
				{ name: 'colors', groups: [ 'colors' ] },
				{ name: 'tools', groups: [ 'tools' ] },
				{ name: 'others', groups: [ 'others' ] },
				{ name: 'about', groups: [ 'about' ] }
		],
		removeButtons : 'Save,NewPage,Templates,Cut,Copy,Paste,Find,Replace,Scayt,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Flash,Iframe,About'
	});

	eventEditor.on( 'fileUploadRequest', function( evt ) {
		var fileLoader = evt.data.fileLoader,
		formData = new FormData(),
		xhr = fileLoader.xhr;
		xhr.open( 'POST', fileLoader.uploadUrl, true );
		formData.append( 'file', fileLoader.file, fileLoader.fileName );
		fileLoader.xhr.send( formData );
		evt.stop();
	}, null, null, 6 );

	eventEditor.on( 'fileUploadResponse', function( evt ) {
		var resData = JSON.parse(evt.data.fileLoader.xhr.response);
		evt.stop();
		// Ger XHR and response.
		var data = evt.data;
		if ( resData.errorCode == 1 ) {
			// Error occurred during upload.
			data.message = resData.msg;
			evt.cancel();
		} else {
			data.message = resData.msg;
			data.url = resData.data;
		}
	});

	/*
	 * 主题图上传
	 */
	var topicPicLimit = 3;
	var $picContainer = $('.topic-pic-container');
	var $thumbTpl = $('.tpl',$picContainer);
	var topicPicUploader = new PicUploader({
		success: function(obj) {
			var picUrl = obj['data'];
			var $thumb = $thumbTpl.clone().removeClass('tpl').css('background-image','url('+picUrl+')');
			$thumb.find('input').val(picUrl);
			$thumbTpl.before($thumb);
		}
	});
	$('#add-pic-btn').on('click',function(){
		if($('.pic:visible',$picContainer).length >= topicPicLimit) {
			greeting({
				title: '提示',
				msg: '只能上传'+ topicPicLimit + '张主题图'
			});		
		} else {
			topicPicUploader.start();	
		}
	});	
	$picContainer.on('click','.pic',function(){
		var $this = $(this);
		actionConfirm({
			msg: '确定删除这个主题图吗？',
			confirm: function(){
				$this.fadeOut({
					complete: function() {
						$this.remove();
					}
				});
			}
		});
	});

	/*
	 * 地图
	 */
	var $suggest = $('#event-location');
	var map = new BMap.Map('event-map');
	map.setMapStyle({
		style: 'light'
	});
	setMarker(new BMap.Point($suggest.attr('data-lng'),$suggest.attr('data-lat')));
	var ac = new BMap.Autocomplete({
		"input" : $suggest.get(0),
		"location" : map
	});
	ac.setInputValue($suggest.attr('data-location-txt'));

	ac.addEventListener("onconfirm", function(e) {
		var _value = e.item.value;
		var locationStr = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		/*智能搜索*/
		var local = new BMap.LocalSearch(map, { 
			onSearchComplete: function() {
				/*获取第一个智能搜索的结果*/
				var pp = local.getResults().getPoi(0).point;
				$('#lng').val(pp.lng);
				$('#lat').val(pp.lat);
				setMarker(pp);
		    } 
		});
		local.search(locationStr);
	});

	function setMarker(point) {
		/* 清除地图上所有覆盖物 */
		map.clearOverlays();
		var marker = new BMap.Marker(point);
		var infoWindow = new BMap.InfoWindow('活动地点');
		map.addOverlay(marker);
		map.addOverlay(infoWindow);
		map.centerAndZoom(point, 18);
		marker.openInfoWindow(infoWindow);
	}
	
	/*
	 * 增加嘉宾
	 */
	var $guestModal = $('#guest-modal');
	$guestModal.modal({
		backdrop: 'static',
		keyboard: false,	
		show: false
	});
	$('#'+$('#user-type-radio :radio:checked').attr('data-target')).show();
	$('#user-type-radio :radio').on('change',function(){
		var $this = $(this);
		var $panelToShow = $('#'+$this.attr('data-target')); 
		$('.guest-panel:visible').slideUp();
		$panelToShow.slideDown();
	});
	$('#add-guest-btn').on('click',function(){
		$guestModal.modal('show');
	});

	var $addGuestForm = $('#add-guest-form');
	var $guestContainer = $('#guest-container');
	$guestContainer.on('click','.btn-remove',function(){
		var $this = $(this);
		actionConfirm({
			msg: '确定删除这个嘉宾吗？',
			confirm: function(){
				$this.fadeOut({
					complete: function() {
						$this.remove();
					}
				});
			}
		});
	});
	$('.form-group label',$addGuestForm).append('<span></span>');
	$guestContainer.popover({
		selector: '.btn-remove',
		trigger: 'hover',
		html: true,
		content: function() {
			var $this = $(this);
			var html = '<div>'+
							'<p>姓名:'+$this.find('[name="name"]').val()+'</p>'+
							'<p>公司:'+$this.find('[name="company"]').val()+'</p>'+
							'<p>职务:'+$this.find('[name="position"]').val()+'</p>'+
							'<p>简介:'+$this.find('[name="introduction"]').val()+'</p>'+
						'</div>';
			return html;
		}
	});
	$addGuestForm.validate({
		debug: true,
		errorClass: 'has-error',
		ignore: '.ignore',
		submitHandler: function() {
			var inputDataObj = {};
			var tpl = $('#guest-tpl').html();
			$(':input',$addGuestForm).each(function(){
				var $this = $(this);
				inputDataObj[$this.attr('name')] = $this.val();
			});
			var $guestEle = swig.render(tpl,{locals:inputDataObj});
			$guestContainer.prepend($guestEle);
			$guestModal.modal('hide');
			$(':input',$addGuestForm).val('');
			$guestAvatarUploadBtn.css('background-image','');
		},
		showErrors: function(errorMap,errorList) {
			for(var index in errorList) {
				var error = errorList[index];
				var $ele = $(error.element);
				if($ele.attr('name') == 'head_url') {
					$guestAvatarUploadBtn.tooltip('show');
				} else {
					$ele.parent().addClass('has-error');
					$ele.siblings('label').find('span').html(' ('+error.message+')').show();
				}
			}
		}
	});		

	$('#nonapp-guest .confirm-btn').on('click',function(){
		var $errEle = $('.has-error',$addGuestForm);
		$errEle.removeClass('has-error').find('label span').hide();
		$addGuestForm.submit();
	});

	/* 上传头像 */
	var $guestAvatarUploadBtn = $('#guest-avatar-upload');
	$guestAvatarUploadBtn.tooltip({
		title:'必须上传头像',
		placement: 'auto',
		trigger: 'manual',
		container: '#guest-avatar-upload'
	});
	var guestAvatarUploader = new PicUploader({
		success: function(obj) {
			$guestAvatarUploadBtn.css('background-image','url('+obj['data']+')');
			$guestAvatarUploadBtn.siblings('input').val(obj['data']);
			$guestAvatarUploadBtn.tooltip('hide');
		}
	});	
	$guestAvatarUploadBtn.on('click',function(){
		guestAvatarUploader.start();
	});		

	/*
	 * 添加app用户
	 */
	$('.suggest',$guestModal).on('click','a',function(){
		var $this = $(this);
		var tpl = $('#guest-tpl').html();
		var $guestEle = swig.render(tpl,{locals:$this.data('userData')});
		$('#guest-container').prepend($guestEle);
		$guestModal.modal('hide');

		
	});

	$('.app-user-search',$guestModal).on('change',function(){
		var $this = $(this);
		var seachWords = $this.val(); 
		var suggestTplStr = $('#app-guest .tpl').html();
		var $suggestContainer = $('#app-guest .suggest');
		cAjax({
			url: '/base/api/searchUserByName',
			type: 'get',
			data: {
				keywords: seachWords
			},
			success: function(obj) {
				var items = obj['data'];
				$suggestContainer.empty();
				if(items.length == 0){
					$suggestContainer.append("没有结果.");
				}
				for(var index in items) {
					var data = items[index];
					var $itemEle = $(swig.render(suggestTplStr,{locals:{item:data}}));
					$itemEle.data('userData',data);
					$suggestContainer.append($itemEle);		
				}
			}
		});
	});

	
	/*
	 * 行政地区选择器初始化
	 */
	$.getJSON(staticUrl+'/bootstrap-chinese-region/dist/sql_areas.json',function(data){
		for (var i = 0; i < data.length; i++) {
			var area = {id:data[i].id,name:data[i].cname,level:data[i].level,parentId:data[i].upid};
			data[i] = area;
		}
		$('.bs-chinese-region').each(function(){
			var $this = $(this);
			$this.attr('data-result',$this.find('input.address').val());
			$this.chineseRegion('source',data);
		});

		$('.bs-chinese-region').on('changed.bs.chinese-region',function(e,areas){
			  //areas是已选择的地区数据，按先选择的在最前的方式排序。
			  $(this).attr('data-result',areas[areas.length-1]['id']);
		});
	});

	/*
	 * 初始化行业标签
	 */
	$('#industry-tags input').each(function(){
		var self = $(this),
		label = self.next(),
		label_text = label.text();
		label.remove();
		self.iCheck({
			checkboxClass: 'icheckbox_line-green',
			radioClass: 'iradio_line-green',
			insert: '<div class="icheck_line-icon"></div>' + label_text
		});
	});

	var $industryTagContainer = $('#industry-tags');

	$industryTagContainer.on('ifClicked','div[class^="icheckbox"]:not(.checked)',function(){
		var tagCheckedNum = $industryTagContainer.find(':checked').length; 
		console.log(tagCheckedNum);
		if(tagCheckedNum >= 3) {
			var $this = $(this);
			greeting({
				title: '提示',
				msg: '活动类型只能选择3个',
				confirm: function(){
					$this.find('input').iCheck('uncheck');		
				}
			});
		}
	});
	/*
	 * 初始化开机引导图上传按钮
	 */
	var $smi_coverUploading = $('#smi_cover-upload-box .overlay').hide();

	var smi_uploader = new PicUploader({
		success : function(obj) {
			var picUrl = obj['data'];
			$smi_coverUploading.hide();
			$('#sceneMaxImage').val(picUrl);
			$('#smi_thumbnail').css('background-image', 'url(' + picUrl + ')');
		}
	});
	$('#smi_thumbnail').on('click', function() {
		smi_uploader.start();
		$smi_coverUploading.click();
	});
	/*
	 * 初始化现场模式主页底图上传按钮
	 */
	var $sbi_coverUploading = $('#sbi_cover-upload-box .overlay').hide();

	var sbi_uploader = new PicUploader({
		success : function(obj) {
			var picUrl = obj['data'];
			$sbi_coverUploading.hide();
			$('#sceneBackImage').val(picUrl);
			$('#sbi_thumbnail').css('background-image', 'url(' + picUrl + ')');
		}
	});
	$('#sbi_thumbnail').on('click', function() {
		sbi_uploader.start();
		$sbi_coverUploading.click();
	});
	
	//是否是现场活动
	$('input[name="isScene"]').on("change",function(){
	    if($(this).val() == 1){
	        $("#scene_img").show();//控制下边那两个 显示
	    }
	    else{
	        $("#scene_img").hide();//控制下边那两个 隐藏
	    }
	});

});
